package com.knowledgeqa.system.controller;

import com.knowledgeqa.system.entity.CoinTransaction;
import com.knowledgeqa.system.service.CoinTransactionService;
import com.knowledgeqa.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 金币交易控制器
 */
@RestController
@RequestMapping("/api/coin")
public class CoinTransactionController {

    @Autowired
    private CoinTransactionService coinTransactionService;

    @Autowired
    private UserService userService;

    /**
     * 金币充值
     */
    @PostMapping("/recharge")
    public ResponseEntity<Map<String, Object>> recharge(@RequestBody Map<String, Object> rechargeInfo) {
        Long userId = Long.valueOf(rechargeInfo.get("userId").toString());
        Integer amount = Integer.valueOf(rechargeInfo.get("amount").toString());

        Map<String, Object> result = new HashMap<>();
        // 更新用户金币余额
        boolean success = userService.rechargeCoin(userId, amount);
        if (success) {
            // 创建充值记录
            coinTransactionService.createTransaction(userId, amount, 0, "金币充值");
            result.put("success", true);
            result.put("message", "充值成功");
        } else {
            result.put("success", false);
            result.put("message", "充值失败");
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 查询用户的金币交易记录
     */
    @GetMapping("/transactions/{userId}")
    public ResponseEntity<Map<String, Object>> getTransactions(@PathVariable Long userId) {
        Map<String, Object> result = new HashMap<>();
        List<CoinTransaction> transactions = coinTransactionService.findByUserId(userId);
        result.put("success", true);
        result.put("transactions", transactions);
        return ResponseEntity.ok(result);
    }

    /**
     * 查询用户的金币充值记录
     */
    @GetMapping("/recharge-records/{userId}")
    public ResponseEntity<Map<String, Object>> getRechargeRecords(@PathVariable Long userId) {
        Map<String, Object> result = new HashMap<>();
        List<CoinTransaction> records = coinTransactionService.findRechargeRecords(userId);
        result.put("success", true);
        result.put("records", records);
        return ResponseEntity.ok(result);
    }

    /**
     * 查询用户的金币消费记录
     */
    @GetMapping("/consume-records/{userId}")
    public ResponseEntity<Map<String, Object>> getConsumeRecords(@PathVariable Long userId) {
        Map<String, Object> result = new HashMap<>();
        List<CoinTransaction> records = coinTransactionService.findConsumeRecords(userId);
        result.put("success", true);
        result.put("records", records);
        return ResponseEntity.ok(result);
    }
}